package yxy.game.pm2.command.guard;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.AreaModule;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.GuardMessage;
import yxy.game.pm2.module.guard.GuardHandle;
import yxy.game.pm2.module.guard.GuardModule;
import yxy.game.pm2.module.guard.GuardPlayerModule;

/** 洛阳守卫 洛阳守卫操作 */
@MessageType(proto = Command.GuardOperate, classtype = GuardMessage.GuardOperateRequest.class)
public class CMD_GuardOperate extends Command<GuardMessage.GuardOperateRequest> {

	@Override
	public void execute(MessageSource messageSource, GuardMessage.GuardOperateRequest request) {
		String playerCode = messageSource.getTag();
		int operation = request.getOperation();

		GuardMessage.GuardOperateResponse.Builder response = GuardMessage.GuardOperateResponse.newBuilder();

		AreaBean areaBean = AreaModule.area(playerCode);

		RedisLock lock = GuardModule.lock(areaBean.getAreaId());
		RedisLock lockp = GuardPlayerModule.lock(playerCode);
		try {
			if (lock.tryLock() && lockp.tryLock()) {
				Result result = new GuardHandle().operate(playerCode, operation, response);
				send(messageSource, response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			lock.unlock();
			lockp.unlock();
		}
	}

	private void send(MessageSource messageSource, GuardMessage.GuardOperateResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}